package com.rainbow.common.event.config;

import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.EventBus;
import com.rainbow.common.core.toolkit.SpringBeanUtil;
import com.rainbow.common.event.annotation.MessageEventBus;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

/**
 * eventBus总线执行器
 * @author 傅为地
 */
@Component
public class EventBusTemplate {

    /**
     * 同步事件处理器
     */
    @Resource
    private EventBus syncEventBus;

    /**
     * 异步事件处理器
     */
    @Resource
    private AsyncEventBus asyncEventBus;

    /**
     * 发送异步通知
     * @param event 事件
     */
    public void postSync(Object event) {
        syncEventBus.post(event);
    }

    /**
     * 发送同步通知
     * @param event 事件
     */
    public void postAsync(Object event) {
        asyncEventBus.post(event);
    }

    /**
     * 初始化监听器注册
     */
    @PostConstruct
    public void initialize() {
        List<Object> listeners = SpringBeanUtil.getBeansWithAnnotation(MessageEventBus.class);
        for (Object listener : listeners) {
            asyncEventBus.register(listener);
            syncEventBus.register(listener);
        }
    }
}